from flask import Blueprint
from flask import jsonify, request
from sqlalchemy import desc

from db import db
from db.models import UserImage
from utils.file import get_image_path

user_image_api = Blueprint('user_image_api', __name__)

# 默认的壁纸，在没有找到是时候使用，增加容错
DEFAULT_WALLPAPER = 'ai.png'


def save_image_info_to_db(uid, save_path):
    # 创建新的图片信息记录
    new_image_info = UserImage(uid=uid, save_path=save_path)

    # 添加到数据库会话并提交
    db.session.add(new_image_info)
    db.session.commit()

    # 判断是否添加成功
    if new_image_info.id:
        return True
    else:
        return False


# 查询用户当前设置的壁纸
@user_image_api.route('/v1/get_wallpaper', methods=['GET'])
def get_wallpaper():
    uid = request.args.get('uid')
    if uid is None:
        return jsonify({
            'code': 400,
            'message': "用户id不能为空",
            'data': ''
        })
    user_image = UserImage.query.filter_by(uid=uid, is_wallpaper=1).first()
    if user_image:
        filename = user_image.save_path
    else:
        filename = DEFAULT_WALLPAPER
    return jsonify({
        'code': 200,
        'message': "success",
        'data': get_image_path(filename)
    })


@user_image_api.route('/v1/set_wallpaper', methods=['POST'])
def set_wallpaper():
    _id = request.json.get('id')
    uid = request.json.get('uid')
    is_wallpaper = request.json.get('is_wallpaper')

    if _id is None or uid is None or is_wallpaper is None:
        return jsonify({
            'code': 500,
            'message': "参数错误",
            'data': ''
        })

    print(f"Received request to set wallpaper with id: {_id}, uid: {uid}, is_wallpaper: {is_wallpaper}")

    # 如果设置为壁纸，先将该用户之前的壁纸设置为非壁纸
    if is_wallpaper:
        UserImage.query.filter_by(uid=uid, is_wallpaper=True).update({'is_wallpaper': False})

    # 更新指定图片的壁纸状态
    image_info = UserImage.query.filter_by(id=_id, uid=uid).first()
    if image_info:
        image_info.is_wallpaper = is_wallpaper
        db.session.commit()
        return jsonify({
            'code': 200,
            'message': '壁纸设置成功',
            'data': ''
        })
    else:
        return jsonify({
            'code': 404,
            'message': '图片未找到',
            'data': ''
        })


@user_image_api.route('/v1/delete_image', methods=['POST'])
def delete_image():
    _id = request.json.get('id')
    uid = request.json.get('uid')

    if _id is None or uid is None:
        return jsonify({
            'code': 500,
            'message': "参数错误",
            'data': ''
        })

    print(f"Received request to delete image with id: {_id}, uid: {uid}")

    # 逻辑删除指定图片
    image_info = UserImage.query.filter_by(id=_id, uid=uid).first()
    if image_info:
        image_info.is_deleted = True
        db.session.commit()
        return jsonify({
            'code': 200,
            'message': '图片删除成功',
            'data': ''
        })
    else:
        return jsonify({
            'code': 404,
            'message': '图片未找到',
            'data': ''
        })


@user_image_api.route('/v1/list_images', methods=['GET'])
def list_images():
    uid = request.args.get('uid')

    if uid is None:
        return jsonify({
            'code': 500,
            'message': "参数错误",
            'data': ''
        })
    print(f"Received request to delete image with uid: {uid}")

    # 查询指定用户的图片列表，排除逻辑删除的图片
    images = UserImage.query.filter_by(uid=uid, is_deleted=False).order_by(desc(UserImage.id)).limit(10).all()
    print("image list:", images)

    # 构建返回数据
    image_list = [{
        'id': image.id,
        'save_path': get_image_path(image.save_path),
        'is_wallpaper': image.is_wallpaper,
        'created_time': image.created_time,
        'updated_time': image.updated_time
    } for image in images]

    return jsonify({
        'code': 200,
        'message': '',
        'data': image_list
    })


# 保存图片
@user_image_api.route('/v1/save_image', methods=['POST'])
def save_image():
    uid = request.json.get('uid')
    filename = request.json.get('save_path')
    if uid is None or filename is None:
        return jsonify({
            'code': 500,
            'message': "参数错误",
            'data': ''
        })
    print(f"Received request to save image with filename: {filename}, uid: {uid}")

    # 查找对应的图片信息
    image_info = UserImage.query.filter_by(uid=uid, save_path=filename).first()
    if image_info:
        res = UserImage.query.filter_by(uid=uid, save_path=filename).update({'is_save': True})
        print("update image res:", res)
        db.session.commit()
    else:
        res = save_image_info_to_db(uid, filename)
        print("insert image res:", res)

    return jsonify({
        'code': 200,
        'message': '保存成功',
        'data': ''
    })
